﻿using System;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Xml;

namespace Homework6
{
    public partial class Form1 : Form
    {
        private TreeView treeView;
        private ListView listView;
        private ToolStrip toolStrip;
        private StatusStrip statusStrip;

        public Form1()
        {
            try
            {
                InitializeComponent();
                InitializeUI();
                LoadUserDirectory();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"初始化错误: {ex.Message}", "错误", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void InitializeUI()
        {
            try
            {
                //主窗体
                Text = "文件浏览器";
                Size = new Size(900, 600);
                StartPosition = FormStartPosition.CenterScreen;

                //菜单栏
                MenuStrip menuStrip = new MenuStrip();
                ToolStripMenuItem fileMenu = new ToolStripMenuItem("文件(&F)");
                ToolStripMenuItem viewMenu = new ToolStripMenuItem("查看(&V)");
                ToolStripMenuItem helpMenu = new ToolStripMenuItem("帮助(&H)");

                //菜单项
                ToolStripMenuItem refreshItem = new ToolStripMenuItem("刷新", null, (s, e) => LoadUserDirectory());
                ToolStripMenuItem exitItem = new ToolStripMenuItem("退出", null, (s, e) => Application.Exit());
                fileMenu.DropDownItems.Add(refreshItem);
                fileMenu.DropDownItems.Add(new ToolStripSeparator());
                fileMenu.DropDownItems.Add(exitItem);

                //查看菜单项
                ToolStripMenuItem detailsView = new ToolStripMenuItem("详细信息", null, (s, e) => listView.View = View.Details);
                ToolStripMenuItem listViewItem = new ToolStripMenuItem("列表", null, (s, e) => listView.View = View.List);
                ToolStripMenuItem largeIconView = new ToolStripMenuItem("大图标", null, (s, e) => listView.View = View.LargeIcon);
                viewMenu.DropDownItems.Add(detailsView);
                viewMenu.DropDownItems.Add(listViewItem);
                viewMenu.DropDownItems.Add(largeIconView);

                //帮助菜单项
                ToolStripMenuItem aboutItem = new ToolStripMenuItem("关于", null, ShowAboutDialog);
                helpMenu.DropDownItems.Add(aboutItem);

                menuStrip.Items.Add(fileMenu);
                menuStrip.Items.Add(viewMenu);
                menuStrip.Items.Add(helpMenu);
                Controls.Add(menuStrip);

                //工具栏
                toolStrip = new ToolStrip();
                toolStrip.Items.Add(new ToolStripButton("刷新", null, (s, e) => LoadUserDirectory()));
                toolStrip.Items.Add(new ToolStripSeparator());
                toolStrip.Items.Add(new ToolStripButton("向上", null, GoUpDirectory));
                Controls.Add(toolStrip);

                //分割容器
                SplitContainer splitContainer = new SplitContainer();
                splitContainer.Dock = DockStyle.Fill;
                splitContainer.Panel1MinSize = 100;
                splitContainer.Panel2MinSize = 100;
                // 确保SplitterDistance在有效范围内
                int maxSplitterDistance = ClientSize.Width - splitContainer.Panel2MinSize;
                int minSplitterDistance = splitContainer.Panel1MinSize;
                int splitterDistance = 300;
                
                if (splitterDistance > maxSplitterDistance)
                    splitterDistance = maxSplitterDistance;
                if (splitterDistance < minSplitterDistance)
                    splitterDistance = minSplitterDistance;
                    
                splitContainer.SplitterDistance = splitterDistance;
                Controls.Add(splitContainer);

                //树形视图
                treeView = new TreeView();
                treeView.Dock = DockStyle.Fill;
                treeView.AfterSelect += TreeView_AfterSelect;
                splitContainer.Panel1.Controls.Add(treeView);

                //列表视图
                listView = new ListView();
                listView.Dock = DockStyle.Fill;
                listView.View = View.Details;
                listView.FullRowSelect = true;
                listView.Columns.Add("名称", 250);
                listView.Columns.Add("类型", 120);
                listView.Columns.Add("修改日期", 150);
                listView.Columns.Add("大小", 100);
                listView.DoubleClick += ListView_DoubleClick;
                splitContainer.Panel2.Controls.Add(listView);

                //状态栏
                statusStrip = new StatusStrip();
                statusStrip.Items.Add(new ToolStripStatusLabel("就绪"));
                Controls.Add(statusStrip);

                //控件位置
                menuStrip.Location = new Point(0, 0);
                toolStrip.Location = new Point(0, menuStrip.Height);
                splitContainer.Location = new Point(0, menuStrip.Height + toolStrip.Height);
                splitContainer.Height = ClientSize.Height - menuStrip.Height - toolStrip.Height - statusStrip.Height;
                statusStrip.Location = new Point(0, ClientSize.Height - statusStrip.Height);
                
                // 创建ImageList
                ImageList imgList = new ImageList();
                listView.SmallImageList = imgList;
                treeView.ImageList = imgList;
                
                // 尝试从文件系统加载图标
                string exePath = AppDomain.CurrentDomain.BaseDirectory;
                string resourcesPath = Path.Combine(exePath, "Resources");
                
                if (Directory.Exists(resourcesPath))
                {
                    string folderIconPath = Path.Combine(resourcesPath, "1.png");
                    string fileIconPath = Path.Combine(resourcesPath, "2.png");
                    
                    if (File.Exists(folderIconPath) && File.Exists(fileIconPath))
                    {
                        imgList.Images.Add("folder", Image.FromFile(folderIconPath));
                        imgList.Images.Add("file", Image.FromFile(fileIconPath));
                    }
                    else
                    {
                        // 使用系统图标
                        imgList.Images.Add("folder", SystemIcons.Application.ToBitmap());
                        imgList.Images.Add("file", SystemIcons.WinLogo.ToBitmap());
                    }
                }
                else
                {
                    // 使用系统图标
                    imgList.Images.Add("folder", SystemIcons.Application.ToBitmap());
                    imgList.Images.Add("file", SystemIcons.WinLogo.ToBitmap());
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"UI初始化错误: {ex.Message}", "错误", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void LoadUserDirectory()
        {
            try
            {
                if (treeView == null) return;
                
                treeView.Nodes.Clear();
                string userPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);

                TreeNode rootNode = new TreeNode(Path.GetFileName(userPath));
                rootNode.ImageIndex = 0;
                rootNode.SelectedImageIndex = 0;
                rootNode.Tag = userPath;

                treeView.Nodes.Add(rootNode);
                LoadSubDirectories(rootNode);
                rootNode.Expand();
                treeView.SelectedNode = rootNode;
                UpdateStatus($"已加载: {userPath}");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载目录错误: {ex.Message}", "错误", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void LoadSubDirectories(TreeNode parentNode)
        {
            if (parentNode == null || parentNode.Tag == null) return;
            
            try
            {
                string path = parentNode.Tag.ToString();
                if (!Directory.Exists(path)) return;
                
                foreach (string dir in Directory.GetDirectories(path))
                {
                    TreeNode node = new TreeNode(Path.GetFileName(dir));
                    node.ImageIndex = 0;
                    node.SelectedImageIndex = 0;
                    node.Tag = dir;
                    parentNode.Nodes.Add(node);

                    try
                    {
                        foreach (string subDir in Directory.GetDirectories(dir))
                        {
                            TreeNode subNode = new TreeNode(Path.GetFileName(subDir));
                            subNode.ImageIndex = 0;
                            subNode.SelectedImageIndex = 0;
                            subNode.Tag = subDir;
                            node.Nodes.Add(subNode);
                        }
                    }
                    catch { }
                }
            }
            catch (UnauthorizedAccessException)
            {
                //不处理
            }
            catch (Exception)
            {
                //不处理其他异常
            }
        }

        private void TreeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (listView == null || e == null || e.Node == null || e.Node.Tag == null) return;
            
            listView.Items.Clear();
            string currentPath = e.Node.Tag.ToString();
            if (!Directory.Exists(currentPath)) return;

            try
            {
                //添加子目录
                foreach (string dir in Directory.GetDirectories(currentPath))
                {
                    DirectoryInfo di = new DirectoryInfo(dir);
                    ListViewItem item = new ListViewItem(di.Name, 0);
                    item.SubItems.Add("文件夹");
                    item.SubItems.Add(di.LastWriteTime.ToString("yyyy-MM-dd HH:mm"));
                    item.SubItems.Add("");
                    item.Tag = dir;
                    listView.Items.Add(item);
                }

                //添加文件
                foreach (string file in Directory.GetFiles(currentPath))
                {
                    FileInfo fi = new FileInfo(file);
                    ListViewItem item = new ListViewItem(fi.Name, 1);
                    item.SubItems.Add($"{fi.Extension.ToUpper().TrimStart('.')} 文件");
                    item.SubItems.Add(fi.LastWriteTime.ToString("yyyy-MM-dd HH:mm"));
                    item.SubItems.Add(fi.Length > 1024 ?
                        $"{(fi.Length / 1024.0):N1} KB" : $"{fi.Length} 字节");
                    item.Tag = file;
                    listView.Items.Add(item);
                }

                UpdateStatus($"已加载: {currentPath} | 项目: {listView.Items.Count}");
            }
            catch (UnauthorizedAccessException)
            {
                UpdateStatus("错误: 访问被拒绝");
            }
            catch (Exception ex)
            {
                UpdateStatus($"错误: {ex.Message}");
            }
        }

        private void ListView_DoubleClick(object sender, EventArgs e)
        {
            if (listView == null || listView.SelectedItems.Count == 0 || 
                listView.SelectedItems[0].Tag == null) return;

            string path = listView.SelectedItems[0].Tag.ToString();

            if (Directory.Exists(path))
            {
                //文件夹在树视图中定位
                FindAndSelectTreeNode(treeView.Nodes[0], path);
            }
            else if (Path.GetExtension(path).Equals(".xml", StringComparison.OrdinalIgnoreCase))
            {
                //XML文件解析内容
                ParseXmlFile(path);
            }
            else
            {
                try
                {
                    System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
                    {
                        FileName = path,
                        UseShellExecute = true
                    });
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"无法打开文件:\n{ex.Message}", "错误",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void GoUpDirectory(object sender, EventArgs e)
        {
            if (treeView == null || treeView.SelectedNode == null || 
                treeView.SelectedNode.Parent == null) return;
                
            treeView.SelectedNode = treeView.SelectedNode.Parent;
        }

        private bool FindAndSelectTreeNode(TreeNode node, string path)
        {
            if (node == null || node.Tag == null || treeView == null || 
                string.IsNullOrEmpty(path)) return false;
                
            if (node.Tag.ToString().Equals(path, StringComparison.OrdinalIgnoreCase))
            {
                treeView.SelectedNode = node;
                node.Expand();
                return true;
            }

            foreach (TreeNode child in node.Nodes)
            {
                if (FindAndSelectTreeNode(child, path))
                    return true;
            }
            return false;
        }

        private void ParseXmlFile(string filePath)
        {
            if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath)) return;
            
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(filePath);

                Form xmlViewer = new Form();
                xmlViewer.Text = $"XML查看器 - {Path.GetFileName(filePath)}";
                xmlViewer.Size = new Size(600, 500);
                xmlViewer.StartPosition = FormStartPosition.CenterParent;

                TreeView xmlTree = new TreeView();
                xmlTree.Dock = DockStyle.Fill;
                xmlTree.Font = new Font("Consolas", 10);
                TreeNode root = new TreeNode("XML文档");
                xmlTree.Nodes.Add(root);
                BuildXmlTree(doc.DocumentElement, root);

                xmlTree.ExpandAll();
                xmlViewer.Controls.Add(xmlTree);
                xmlViewer.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"XML解析错误:\n{ex.Message}", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void BuildXmlTree(XmlNode xmlNode, TreeNode treeNode)
        {
            if (xmlNode == null || treeNode == null) return;

            TreeNode newNode = new TreeNode(xmlNode.Name);
            newNode.Tag = xmlNode;

            if (xmlNode.Attributes != null)
            {
                foreach (XmlAttribute attr in xmlNode.Attributes)
                {
                    TreeNode attrNode = new TreeNode($"@{attr.Name} = \"{attr.Value}\"");
                    attrNode.ForeColor = Color.Blue;
                    newNode.Nodes.Add(attrNode);
                }
            }

            //添加文本内容
            if (!string.IsNullOrWhiteSpace(xmlNode.InnerText)
                && xmlNode.ChildNodes.Count == 1
                && xmlNode.FirstChild.NodeType == XmlNodeType.Text)
            {
                string text = xmlNode.InnerText.Trim();
                if (text.Length > 50) text = text.Substring(0, 47) + "...";

                TreeNode textNode = new TreeNode($"文本: \"{text}\"");
                textNode.ForeColor = Color.Green;
                newNode.Nodes.Add(textNode);
            }

            foreach (XmlNode childNode in xmlNode.ChildNodes)
            {
                if (childNode.NodeType == XmlNodeType.Element)
                {
                    BuildXmlTree(childNode, newNode);
                }
            }

            treeNode.Nodes.Add(newNode);
        }

        private void UpdateStatus(string message)
        {
            if (statusStrip == null || statusStrip.Items.Count == 0) return;
            
            statusStrip.Items[0].Text = message;
        }

        private void ShowAboutDialog(object sender, EventArgs e)
        {
            MessageBox.Show(
                "文件浏览器 v1.0\n\n" +
                "功能:\n" +
                "- 浏览文件和文件夹\n" +
                "- 查看文件详细信息\n" +
                "- 解析XML文件内容\n\n" +
                "© 2023 文件浏览器项目",
                "关于",
                MessageBoxButtons.OK,
                MessageBoxIcon.Information
            );
        }
    }
}
